package main

import (
	"archive/zip"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
)

func zipFiles(outputFilePath string, files []string) error {
	zipFile, err := os.Create(outputFilePath)
	if err != nil {
		return err
	}
	defer zipFile.Close()

	zipWriter := zip.NewWriter(zipFile)
	defer zipWriter.Close()

	for _, file := range files {
		if err := addFileToZip(zipWriter, file); err != nil {
			return err
		}
	}

	return nil
}

func addFileToZip(zipWriter *zip.Writer, filePath string) error {
	file, err := os.Open(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	// 获取文件信息
	info, err := file.Stat()
	if err != nil {
		return err
	}

	// 创建zip文件内的文件头
	header, err := zip.FileInfoHeader(info)
	if err != nil {
		return err
	}

	// 修改文件头中的文件名
	header.Name = filepath.Base(filePath)

	// 将文件头写入zip文件
	writer, err := zipWriter.CreateHeader(header)
	if err != nil {
		return err
	}

	// 将文件内容拷贝到zip文件
	_, err = io.Copy(writer, file)
	return err
}

func GenZip(sourceDir, outputZipFile string) error {

	// 获取目录下所有.conf文件
	var confFiles []string
	err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if !info.IsDir() && strings.HasSuffix(info.Name(), ".conf") {
			confFiles = append(confFiles, path)
		}

		return nil
	})

	if err != nil {
		fmt.Printf("Error walking the path %v: %v\n", sourceDir, err)
		return err
	}

	// 压缩成zip包
	err = zipFiles(outputZipFile, confFiles)
	if err != nil {
		fmt.Printf("Error zipping files: %v\n", err)
		return err
	}

	fmt.Printf("Zip file created successfully: %s\n", outputZipFile)
	return nil
}
